package com.meowcook.service.impl;

import com.meowcook.exception.AppException;
import com.meowcook.common.AppResult;
import com.meowcook.common.ResultCode;
import com.meowcook.dao.CollectionMapper;
import com.meowcook.dao.RecipeMapper;
import com.meowcook.mapper.CollectionPojoMapper;
import com.meowcook.pojo.dto.CollectionDTO;
import com.meowcook.pojo.po.Collection;
import com.meowcook.pojo.po.Recipe;
import com.meowcook.pojo.vo.CollectionVO;
import com.meowcook.service.ICollectionService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
 * Created with Intellij IDEA.
 * Description:
 * User: 28792
 * Date: 2025-05-16
 * Time: 14:02
 */
@Service
public class CollectionServiceImpl implements ICollectionService {
    @Resource
    private CollectionMapper collectionMapper;
    @Resource
    private CollectionPojoMapper collectionPojoMapper;
    @Resource
    private RecipeMapper recipeMapper;
    @Override
    public CollectionVO selectCollectionRecord(Long userId, Long recipeId) {
        Collection collection = collectionMapper.selectByUserIdAndRecipeId(userId, recipeId);
        if (collection == null) return null;
        return collectionPojoMapper.toVO(collection);
    }

    @Override
    public void collect(CollectionDTO collectionDTO) {
        // 数据转化
        Collection collection = collectionPojoMapper.toPO(collectionDTO);
        // id 为空则新增收藏关联，不为空则更新收藏状态
        if (collection.getId() == null) {
            collection.setCreateTime(new Date());
            collection.setUpdateTime(new Date());
            int row = collectionMapper.insertSelective(collection);
            if (row != 1) throw new AppException(AppResult.fail(ResultCode.ERROR_SERVICE));
        } else {
            collection.setRecipeId(null);
            collection.setUserId(null);
            collection.setUpdateTime(new Date());
            int row = collectionMapper.updateByPrimaryKeySelective(collection);
            if (row != 1) throw new AppException(AppResult.fail(ResultCode.ERROR_SERVICE));
        }
        // 更新食谱收藏数
        Recipe recipe = recipeMapper.selectByPrimaryKey(collectionDTO.getRecipeId());
        Recipe updateRecipe = new Recipe();
        updateRecipe.setId(recipe.getId());
        if (collectionDTO.getId() == null || collectionDTO.getIsDeleted() == 0) {
            updateRecipe.setCollectCount(recipe.getCollectCount() + 1);
            int row = recipeMapper.updateByPrimaryKeySelective(updateRecipe);
            if (row != 1) throw new AppException(AppResult.fail(ResultCode.ERROR_SERVICE));
        }
        if (collectionDTO.getIsDeleted() == 1) {
            updateRecipe.setCollectCount(recipe.getCollectCount() - 1);
            int row = recipeMapper.updateByPrimaryKeySelective(updateRecipe);
            if (row != 1) throw new AppException(AppResult.fail(ResultCode.ERROR_SERVICE));
        }
    }
}
